package com.boot.configstatistical.repair;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;

/**
 * @author songlin.an
 * @className HttpClientUtils
 * @description TODO
 * @date 2023/5/18 12:00
 **/
public class HttpClientUtils {
    private static final int MAX_TOTAL_CONNECTIONS = 200;
    private static final int MAX_CONNECTIONS_PER_ROUTE = 20;
    private static final int SOCKET_TIMEOUT_MILLIS = 30000;
    private static final int CONNECT_TIMEOUT_MILLIS = 30000;

    private static HttpClient httpClient;

    static {
        // 创建连接池管理器
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(MAX_TOTAL_CONNECTIONS);
        cm.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE);

        // 创建HttpClient客户端
        httpClient = HttpClientBuilder.create()
                .setConnectionManager(cm)
                .build();
    }

    /**
     * 发送GET请求，并返回响应字符串
     *
     * @param url 要请求的URL
     * @return 响应字符串
     * @throws IOException HTTP请求失败时抛出
     * @throws URISyntaxException URL格式不合法时抛出
     */
    public static String doGet(String url) throws IOException, URISyntaxException {
        // 构建请求URI
        URIBuilder uriBuilder = new URIBuilder(url);
        HttpGet httpGet = new HttpGet(uriBuilder.build());

        // 发送HTTP请求
        String responseString;
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(
                httpClient.execute(httpGet).getEntity().getContent(),
                StandardCharsets.UTF_8))) {
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append(System.lineSeparator());
            }
            responseString = sb.toString();
        }
        return responseString.trim();
    }
}
